from datetime import datetime

from tqsdk import TqSim, TqSimStock, TqApi, TqBacktest, TqMultiAccount, TqAuth, BacktestFinished

tqsim_future = TqSim()
tqsim_stock = TqSimStock()
api = TqApi(account=TqMultiAccount([tqsim_future, tqsim_stock]),
            backtest=TqBacktest(start_dt=datetime(2021, 7, 12), end_dt=datetime(2021, 7, 14)),
            auth=TqAuth("18076605596", "chen1234"))

future_quote = api.get_quote("SHFE.cu2112")
future_stock = api.get_quote("SSE.603666")

while datetime.strptime(future_stock.datetime, "%Y-%m-%d %H:%M:%S.%f") < datetime(2021, 7, 12, 9, 50):
    api.wait_update()

# 开仓，多账户下单，需要指定下单账户
order1 = api.insert_order(symbol="SHFE.cu2112", direction="BUY", offset="OPEN", volume=10, limit_price=future_quote.ask_price1, account=tqsim_future)
order2 = api.insert_order(symbol="SSE.603666", direction="BUY", volume=300, account=tqsim_stock)
while order1.status != 'FINISHED' or order2.status != 'FINISHED':
    api.wait_update()

future_account = tqsim_future.get_account()
stock_account = tqsim_stock.get_account()
# 打印账户当前可用资金
print(future_account.available, stock_account.available)

# 等待行情回测到第二天
while datetime.strptime(future_stock.datetime, "%Y-%m-%d %H:%M:%S.%f") < datetime(2021, 7, 13, 10, 30):
    api.wait_update()
# 平仓，股票只能 T+1 交易
order3 = api.insert_order(symbol="SHFE.cu2112", direction="SELL", offset="CLOSE", volume=8, limit_price=future_quote.bid_price1, account=tqsim_future)
order4 = api.insert_order(symbol="SSE.603666", direction="SELL", volume=200, account=tqsim_stock)
while order3.status != 'FINISHED' or order4.status != 'FINISHED':
    api.wait_update()

try:  # 等到回测结束
    while True:
        api.wait_update()
except BacktestFinished:
    # 打印回测时间内账户交易信息统计结果
    print(tqsim_future.tqsdk_stat)
    print(tqsim_stock.tqsdk_stat)
    api.close()
